# SHARK_GENERATE_CPP ===========================================================
#
# Example usage:
#   find_package(shark)
#   shark_generate_cpp(SHARK_SRCS SHARK_HDRS schema.sk)
#   add_executable(foo main.cpp ${SHARK_SRCS})
#   target_link_libraries(foo PRIVATE shark::shark_static)
#   target_include_directories(foo PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
#
#  If you are not using the RPC features you can use 'shark::shark_static' in the
#  target_link_libraries call
#
# Configuration variables (optional):
#   SHARKC_OUTPUT_DIR
#       Directory to place compiled schema sources (default: CMAKE_CURRENT_BINARY_DIR).
#   SHARKC_IMPORT_DIRS
#       List of additional include directories for the schema compiler.
#       (SHARKC_SRC_PREFIX and SHARK_INCLUDE_DIRECTORY are always included.)
#   SHARKC_SRC_PREFIX
#       Schema file source prefix (default: CMAKE_CURRENT_SOURCE_DIR).
#   SHARKC_FLAGS
#       Additional flags to pass to the schema compiler.
#
# TODO: convert to cmake_parse_arguments

function(SHARK_GENERATE_CPP SOURCES HEADERS)
    if (NOT ARGN)
        message(SEND_ERROR "SHARK_GENERATE_CPP() called without any source files.")
    endif ()
    set(tool_depends ${EMPTY_STRING})
    #Use cmake targets available
    if (TARGET shark)
        if (NOT SHARK_EXECUTABLE)
            set(SHARK_EXECUTABLE $<TARGET_FILE:shark>)
        endif ()
        if (NOT SHARKC_CXX_EXECUTABLE)
            get_target_property(SHARKC_CXX_EXECUTABLE sharkc-cpp KMCMAKE_EXECUTABLE)
        endif ()
        if (NOT SHARK_INCLUDE_DIRECTORY)
            get_target_property(SHARK_INCLUDE_DIRECTORY shark SHARK_INCLUDE_DIRECTORY)
        endif ()
        list(APPEND tool_depends shark sharkc-cpp)
    endif ()
    if (NOT SHARK_EXECUTABLE)
        message(SEND_ERROR "Could not locate shark executable (SHARK_EXECUTABLE).")
    endif ()
    if (NOT SHARKC_CXX_EXECUTABLE)
        message(SEND_ERROR "Could not locate sharkc-cpp executable (SHARKC_CXX_EXECUTABLE).")
    endif ()
    if (NOT SHARK_INCLUDE_DIRECTORY)
        message(SEND_ERROR "Could not locate shark header files (SHARK_INCLUDE_DIRECTORY).")
    endif ()

    if (DEFINED SHARKC_OUTPUT_DIR)
        # Prepend a ':' to get the format for the '-o' flag right
        set(output_dir ":${SHARKC_OUTPUT_DIR}")
    else ()
        set(output_dir ":.")
    endif ()

    if (NOT DEFINED SHARKC_SRC_PREFIX)
        set(SHARKC_SRC_PREFIX "${CMAKE_CURRENT_SOURCE_DIR}")
    endif ()
    get_filename_component(SHARKC_SRC_PREFIX "${SHARKC_SRC_PREFIX}" ABSOLUTE)

    # Default compiler includes. Note that in shark's own test usage of shark_generate_cpp(), these
    # two variables will end up evaluating to the same directory. However, it's difficult to
    # deduplicate them because if SHARK_INCLUDE_DIRECTORY came from the shark_tool target property,
    # then it must be a generator expression in order to handle usages in both the build tree and the
    # install tree. This vastly overcomplicates duplication detection, so the duplication doesn't seem
    # worth fixing.
    set(include_path -I "${SHARKC_SRC_PREFIX}" -I "${SHARK_INCLUDE_DIRECTORY}")

    if (DEFINED SHARKC_IMPORT_DIRS)
        # Append each directory as a series of '-I' flags in ${include_path}
        foreach (directory ${SHARKC_IMPORT_DIRS})
            get_filename_component(absolute_path "${directory}" ABSOLUTE)
            list(APPEND include_path -I "${absolute_path}")
        endforeach ()
    endif ()

    set(${SOURCES})
    set(${HEADERS})
    foreach (schema_file ${ARGN})
        get_filename_component(file_path "${schema_file}" ABSOLUTE)
        get_filename_component(file_dir "${file_path}" PATH)
        if (NOT EXISTS "${file_path}")
            message(FATAL_ERROR "Shark Proto schema file '${file_path}' does not exist!")
        endif ()

        # Figure out where the output files will go
        if (NOT DEFINED SHARKC_OUTPUT_DIR)
            set(SHARKC_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/")
        endif ()
        # Output files are placed in SHARKC_OUTPUT_DIR, at a location as if they were
        # relative to SHARKC_SRC_PREFIX.
        string(LENGTH "${SHARKC_SRC_PREFIX}" prefix_len)
        string(SUBSTRING "${file_path}" 0 ${prefix_len} output_prefix)
        if (NOT "${SHARKC_SRC_PREFIX}" STREQUAL "${output_prefix}")
            message(SEND_ERROR "Could not determine output path for '${schema_file}' ('${file_path}') with source prefix '${SHARKC_SRC_PREFIX}' into '${SHARKC_OUTPUT_DIR}'.")
        endif ()

        string(SUBSTRING "${file_path}" ${prefix_len} -1 output_path)
        set(output_base "${SHARKC_OUTPUT_DIR}${output_path}")

        add_custom_command(
                OUTPUT "${output_base}.cc" "${output_base}.h"
                COMMAND "${SHARK_EXECUTABLE}"
                ARGS compile
                -o ${SHARKC_CXX_EXECUTABLE}${output_dir}
                --src-prefix ${SHARKC_SRC_PREFIX}
                ${include_path}
                ${SHARKC_FLAGS}
                ${file_path}
                DEPENDS "${schema_file}" ${tool_depends}
                COMMENT "Compiling Shark Proto schema ${schema_file}"
                VERBATIM
        )

        list(APPEND ${SOURCES} "${output_base}.cc")
        list(APPEND ${HEADERS} "${output_base}.h")
    endforeach ()

    set_source_files_properties(${${SOURCES}} ${${HEADERS}} PROPERTIES GENERATED TRUE)
    set(${SOURCES} ${${SOURCES}} PARENT_SCOPE)
    set(${HEADERS} ${${HEADERS}} PARENT_SCOPE)
endfunction()
